#!/bin/sh

set -e

# Set docker compose file name
# NOTE: for now hardcoded dev value
# as (maybe) this executable is not intended to be used in production
# TODO source .env file to determine current environemnt and reslve file name based on APP_ENV
DOCKER_COMPOSE_FILE=docker.dev-compose.yml

# Get container id
# TODO resolve container service name (it can be green or blue)
CONTAINER_SERVICE_NAME=web
CONTAINER_ID=$(docker ps | grep ${CONTAINER_SERVICE_NAME} | awk '{print $1}')

##############################################
# Get all user arguments
# example: ./bin/igor.sh up -d translates into `docker compose up -d`
# where `up` - command name to looking for (up == docker compose up), `-d` its arguments
##############################################

# Command to run
INPUT_COMMAND=$1

# Arguments
INPUT_ARGS=${@:2}

##############################################
# Help
##############################################
if [ ${INPUT_COMMAND} == "info" ]; then
    # Show docker version
    echo $(docker -v)

    # Show container id
    if [ ${CONTAINER_ID} ]; then
        echo "App container id: ${CONTAINER_ID}"
    fi

    exit 0
fi

# TODO help

##############################################
# Check if app is running
# Exit otherwise
##############################################
check_if_app_is_running () {
    if [ ! ${CONTAINER_ID} ]; then
        echo "Ah, Igor is not working..."
        exit 1
    fi
}

##############################################
# Proxying docker compose commands
# these commands prefixed with `docker compose`
##############################################
if [ ${INPUT_COMMAND} == "up" ]; then
    docker compose -f ${DOCKER_COMPOSE_FILE} up ${INPUT_ARGS}
fi

if [ ${INPUT_COMMAND} == "down" ]; then
    check_if_app_is_running
    docker compose -f ${DOCKER_COMPOSE_FILE} down ${INPUT_ARGS}
fi

# TODO prod container
#

##############################################
# Proxying docker build commands
# these commands prefixed with `docker build`
##############################################

# TODO dev image
#

# TODO prod image
#

##############################################
# Proxying app commands
# these commands prefixed with `docker exec -it`
##############################################

# Enter shell
if [ ${INPUT_COMMAND} == "bash" ] || [ ${INPUT_COMMAND} == "shell" ]; then
    check_if_app_is_running
    docker exec -it ${CONTAINER_ID} bash
fi

# Enter shell as superuser
if [ ${INPUT_COMMAND} == "root-bash" ] || [ ${INPUT_COMMAND} == "root-shell" ]; then
    check_if_app_is_running
    docker exec -uroot -it ${CONTAINER_ID} bash
fi

# Run composer commands
# TODO

# Run artisan commands
# TODO

# Run tests
# TODO

# Run npm commands
# TODO

# Run bun commands
# TODO

# Run mysql commands
# TODO

# Run mysqldump commands
# TODO

# Run redis commands
# TODO

# Copy caddy certificate
# TODO
